package com.tianhua.amis4j.service.admin;

import com.coderman.model.meta.bean.back.ModuleBean;
import com.coderman.model.meta.bean.back.ProjectBean;
import com.coderman.model.meta.bean.back.WebCodeBean;
import com.tianhua.amis4j.service.utils.ZipUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * date: 2022/5/20
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class WebCodeDownloadService {

    @Autowired
    private WebCodeService webCodeService;

    /**
     * 下载项目维度的完整代码
     * @param projectCode
     * @return
     */
    public String downloadProjectCode(String projectCode){

        List<WebCodeBean> webCodeBeanList = webCodeService.selectByProjectCode(projectCode);
        if(CollectionUtils.isEmpty(webCodeBeanList)){
            return "没有已生成的代码内容,不可下载.";
        }


        Map<String,List<WebCodeBean>> webCodeMap = new HashMap<>();
        for (WebCodeBean webCodeBean : webCodeBeanList){
            String key = webCodeBean.getModuleCode()+"-"+webCodeBean.getApiUrl();
            List<WebCodeBean> webCodeBeanList1 = webCodeMap.get(key);
            if(webCodeBeanList1 == null){
                webCodeBeanList1 = new ArrayList<>();
            }
            webCodeBeanList1.add(webCodeBean);
            webCodeMap.put(key, webCodeBeanList1);
        }

        List<WebCodeBean> targetCodeBeanList = new ArrayList<>();
        for (Map.Entry<String,List<WebCodeBean>> webCodeEntry : webCodeMap.entrySet()){
            List<WebCodeBean> webCodeBeanList1 = webCodeEntry.getValue();
            webCodeBeanList1.sort(Comparator.comparing(WebCodeBean::getVersion).reversed());
            WebCodeBean newVersionCodeBean = webCodeBeanList1.get(0);
            targetCodeBeanList.add(newVersionCodeBean);
        }

        List<File> fileList = new ArrayList<>();
        for (WebCodeBean webCodeBean : targetCodeBeanList){
            String filePath = getCodeFilePath(webCodeBean);
            File file = new File(filePath);
            try {
                FileUtils.write(file,webCodeBean.getWebDslJson(),"utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }

            fileList.add(file);
        }
        FileOutputStream fos2 = null;
        try {
            String zipCodePath = getZipCodeFilePath(projectCode);
            fos2 = new FileOutputStream(zipCodePath);
            ZipUtils.toZip(fileList, fos2);

            return zipCodePath;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        return null;
    }


    /**
     * 获取构建的文件路径和文件名
     * @param webCodeBean
     * @return
     */
    private String getCodeFilePath(WebCodeBean webCodeBean){
        //写文件到项目目录中
        // 获取classpath
        String classpath = null;
        try {
            classpath = ResourceUtils.getURL("classpath:webcode").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SecureRandom random = new SecureRandom();
        if(StringUtils.isEmpty(webCodeBean.getApiUrl())){
            return classpath + "/" + webCodeBean.getProjectCode() + "/" +webCodeBean.getModuleCode() + "/" + random.nextInt(100000) + "." + webCodeBean.getContentType();
        }else {
            return classpath + "/" + webCodeBean.getProjectCode() + "/" +webCodeBean.getModuleCode() + "/" +webCodeBean.getApiUrl().replace("/","").replace("?","")+
                    webCodeBean.getVersion()+"."  + webCodeBean.getContentType();
        }



    }

    /**
     * 获取压缩文件的路径
     * @param projectCode
     * @return
     */
    private String getZipCodeFilePath(String projectCode){
        //写文件到项目目录中
        // 获取classpath
        String classpath = null;
        try {
            classpath = ResourceUtils.getURL("classpath:webcode").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SecureRandom random = new SecureRandom();
        return classpath + "/" + projectCode + "/" + projectCode + random.nextInt(1000000000) + ".zip";

    }



}
